import { createElement } from '../core/vdom.js';

async function compileComponentFile(content) {
  if (typeof content === 'object') {
    // 如果是 JavaScript 对象，直接返回
    return content;
  }

  const templateMatch = content.match(/<template>([\s\S]*?)<\/template>/);
  const scriptMatch = content.match(/<script>([\s\S]*?)<\/script>/);
  const styleMatch = content.match(/<style>([\s\S]*?)<\/style>/);

  const template = templateMatch ? templateMatch[1].trim() : '';
  const script = scriptMatch ? scriptMatch[1].trim() : 'export default {}';
  const style = styleMatch ? styleMatch[1].trim() : '';

  // 简化的脚本解析
  const componentOptions = new Function(`return ${script.replace('export default ', '')}`)();

  componentOptions.template = (data, methods, slots, scopedSlots) => {
    return compileTemplate(template, data, methods, slots, scopedSlots);
  };

  if (style) {
    const styleElement = document.createElement('style');
    styleElement.textContent = style;
    document.head.appendChild(styleElement);
  }

  return componentOptions;
}

function compileTemplate(template, data, methods, slots, scopedSlots) {
  // 处理作用域插槽
  let compiledTemplate = template.replace(/<slot\s+name="(\w+)"(\s+:(\w+)="(\w+)")?>/g, (_, name, __, propName, propValue) => {
    if (propName && propValue) {
      return (scopedSlots[name] && scopedSlots[name]({ [propName]: data[propValue] })) || '';
    }
    return slots[name] || '';
  });

  // 处理默认插槽
  compiledTemplate = compiledTemplate.replace(/<slot(\s+:(\w+)="(\w+)")?>/g, (_, __, propName, propValue) => {
    if (propName && propValue) {
      return (scopedSlots.default && scopedSlots.default({ [propName]: data[propValue] })) || '';
    }
    return slots.default || '';
  });

  // 处理插值和事件绑定
  compiledTemplate = compiledTemplate.replace(/\{\{\s*(\w+)\s*\}\}/g, (_, key) => `${data[key]}`);
  compiledTemplate = compiledTemplate.replace(/@(\w+)="(\w+)"/g, (_, event, method) => `on${event}="${method}"`);

  return createElement('div', {}, [compiledTemplate]);
}

export { compileComponentFile };